package com.slipper.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

public class ImageUtil {
    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    public static void mergeImage(File backgroundFile, int width, int height, 
            File qrCodeFile, int x, int y,  int qrWidth, int qrHeight, File savePath) throws Exception {
        OutputStream os = null;
        try {
            BufferedImage backgroundImage = ImageIO.read(backgroundFile);
            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(backgroundImage, 0, 0, width, height, null);

            // 画被合并的图
            BufferedImage inputImage = ImageIO.read(qrCodeFile);
            g.drawImage(inputImage, x, y, qrWidth, qrHeight, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

            g.dispose();
            os = Files.newOutputStream(savePath.toPath());
            // 生成图片
            ImageIO.write(buffImg, "PNG", os);
        } catch (Exception e) {
            throw new Exception("图片合并失败！", e);
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

    public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
        // 读取原始图片
        BufferedImage image = ImageIO.read(inputFile);

        // 创建一个用于写入压缩后的图片的输出流
        ImageOutputStream os = ImageIO.createImageOutputStream(outputFile);

        // 获取所有支持JPEG格式的ImageWriter对象
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();

        // 设置输出流
        writer.setOutput(os);

        // 设置图片压缩参数
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);

        // 写入压缩后的图片
        writer.write(null, new IIOImage(image, null, null), param);

        // 关闭输出流和ImageWriter
        os.close();
        writer.dispose();
    }
}
